<template>
  <div class="dialog-content" v-if="detail">
    <div class="ad-block card">
      <div class="item"><span class="label">结算人：</span>{{detail.settlementUser}}</div>
      <div class="item"><span class="label">结算电话：</span>{{detail.settlementPhone}}</div>
      <div class="item-l"></div>
      <div class="item"><span class="label">收款合计：</span>{{detail.totalCollectionUn}}</div>
      <div class="item"><span class="label">付款合计：</span>{{detail.totalPaymentUn}}</div>
      <div class="item"><span class="label">应结款：</span>{{detail.totalCheck}}</div>
    </div>
    <div class="ad-block card">
      <el-form :model="form" ref="form" style="flex-direction: row">
        <div class="col" style="margin-top: 0">
          <div class="col-title">凭证</div>
          <div class="item">
            <el-image v-for="(img,index) in detail.images? detail.images.split(','):[]" :key="index" :preview-src-list="detail.images.split(',')" :src="img" class="img">
              <div slot="error" class="image-slot">
               <span style="color: #c0c4cc">暂无图片</span>
              </div>
            </el-image>
          </div>
          <!-- <el-form-item prop="imgList" :rules="{required: true, message:'请上传凭证'}">
            <el-upload action="" list-type="picture-card" multiple drag
              :file-list="images"
              :on-success="imageSuccess"
              :http-request="uploadImages"
              :on-remove="removeImage"
              :on-preview="imagePreview"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item> -->
        </div>
        <div class="item-l"></div>
        <div>
          <div class="col" v-if="detail.createTime">
            <div class="col-title">结算时间</div>
            <div class="item">{{parseTime(detail.createTime)}}</div>
          </div>
          <div class="item-l"></div>
          <div class="col" v-if="detail.realCollectionTime">
            <div class="col-title">实际收付款时间</div>
            <div class="item">{{parseTime(detail.realCollectionTime)}}</div>
          </div>
          <div class="item-l" v-if="detail.remark"></div>
          <div class="col" v-if="detail.remark">
            <div class="col-title">备注</div>
            <div class="item">{{detail.remark}}</div>
          </div>
        </div>
      </el-form>
    </div>
    <el-button type="primary" size="mini" :disabled="cannotEdit" @click="showSettlement">结算</el-button>
    <div class="card" style="padding: 0">
      <ad-table ref="order" :data="detail.checkOrderList" @row-click="orderSelectRow" @selection-change="orderSelectRows" border u-table height="150">
        <ad-table-column type="selection" ctype="selection" fixed/>
        <ad-table-column label="序号" type="index" ctype="index" fixed/>
        <ad-table-column label="订单号" prop="orderSubNo" fixed/>
        <ad-table-column label="运单号" prop="transportNo"/>
        <ad-table-column label="结算状态" prop="status">
          <template v-slot="{row}">
            <span v-if="row.status == 2">未结算</span>
            <span v-if="row.status == 1">已结算</span>
          </template>
        </ad-table-column>
        <ad-table-column label="大板车牌" prop="licensePlateNumber"/>
        <ad-table-column label="制单人" prop="createUserName"/>
        <ad-table-column label="制单时间" prop="createTime" ctype="datetime"/>
        <ad-table-column label="客户" prop="customerName"/>
        <ad-table-column label="联系电话" prop="customerPhone"/>
        <ad-table-column label="收货人" prop="consigneeName"/>
        <ad-table-column label="联系电话" prop="consigneePhone"/>
        <ad-table-column label="出发地" prop="startCode" ctype="city"/>
        <ad-table-column label="目的地" prop="destinationCode" ctype="city"/>
        <ad-table-column label="车型名称" prop="carName"/>
        <ad-table-column label="车架号" prop="vin"/>
        <ad-table-column label="结算金额" prop="financeCheck"/>
<!--        <ad-table-column label="操作" width="120px">-->
<!--          <template v-slot="{row}">-->
<!--            <span style="color: #1F89EB;cursor: pointer" @click="showSettlement(row)">结算</span>-->
<!--          </template>-->
<!--        </ad-table-column>-->
      </ad-table>
<!--      <el-table :data="detail.checkOrderList" border header-cell-class-name="table-th" cell-class-name="table-cell" class="table">-->
<!--        <el-table-column label="子订单号" prop="orderSubNo" show-overflow-tooltip />-->
<!--        <el-table-column label="运单号" prop="transportNo" show-overflow-tooltip />-->
<!--        <el-table-column label="大板车牌" prop="licensePlateNumber" show-overflow-tooltip />-->
<!--        <el-table-column label="制单人" prop="createUserName" show-overflow-tooltip/>-->
<!--        <el-table-column label="制单时间" show-overflow-tooltip><template slot-scope="{row}">{{parseTime(row.createTime)}}</template></el-table-column>-->
<!--        <el-table-column label="客户" prop="customerName" show-overflow-tooltip />-->
<!--        <el-table-column label="联系方式" prop="customerPhone" show-overflow-tooltip />-->
<!--        <el-table-column label="收货人" prop="consigneeName" show-overflow-tooltip />-->
<!--        <el-table-column label="联系方式" prop="consigneePhone" show-overflow-tooltip />-->
<!--&lt;!&ndash;        <el-table-column label="出发地" show-overflow-tooltip><template slot-scope="{row}">{{parseCityCode(row.startCode)[1]}}</template></el-table-column>&ndash;&gt;-->
<!--&lt;!&ndash;        <el-table-column label="目的地" show-overflow-tooltip><template slot-scope="{row}">{{parseCityCode(row.destinationCode)[1]}}</template></el-table-column>&ndash;&gt;-->
<!--        <el-table-column label="车型名称" prop="carName" show-overflow-tooltip />-->
<!--        <el-table-column label="车架号" prop="vin" show-overflow-tooltip />-->
<!--        <el-table-column label="结算金额" prop="financeCheck" show-overflow-tooltip />-->
<!--      </el-table>-->
    </div>
    <div class="form-btns">
      <el-button size="mini" @click="repeal">撤消</el-button>
      <el-button size="mini" @click="exportExcel">导出</el-button>
      <el-button size="mini" ref="print" v-print="'#print-table'">打印</el-button>
      <el-input-number size="mini" v-model="totalPdf" :min="1" :max="9" class="total-pdf" /> 份
      <div id="print-table" style="position: fixed; visibility: hidden;">
        <div >
          <div v-for="(item, index) in totalPdf" :key="index" class="print-table">
            <div class="print-title">安达物流对账单</div>
            <div class="print-head">
              <span>结算人：{{detail.settlementUser}}</span>
              <span>联系方式：{{detail.settlementPhone}}</span>
              <span>实际收付款时间：{{parseTime(detail.realCollectionTime)}}</span>
            </div>
            <table border style="width: 100%">
              <tr>
                <th>子订单号</th><th>制单人</th><th>制单时间</th><th>出发地</th><th>目的地</th><th>车型</th><th>车架号</th>
                <th>未收运费</th><th>未收商务费</th><th>未付提车费</th><th>未付承运费</th><th>未付送货费</th><th>未付其他费用</th><th>未付费用合计</th><th>应结款</th><th>订单备注</th>
              </tr>
              <tr v-for="(row, index) in detail.checkOrderList" :key="index">
                <td><div class="cell"><value :model="row" prop="orderSubNo"/></div></td>
                <td><value :model="row" prop="createUserName"/></td>
                <td><value :model="row" prop="createTime" type="datetime"/></td>
                <td><value :model="row" prop="startCode" type="city"/></td>
                <td><value :model="row" prop="destinationCode" type="city"/></td>
                <td><value :model="row" prop="carName"/></td>
                <td><value :model="row" prop="vin"/></td>
                <td><value :model="row" prop="unCollection"/></td>
                <td><value :model="row" prop="kickbackUn"/></td>
                <td><value :model="row" prop="pickUn"/></td>
                <td><value :model="row" prop="transportUn"/></td>
                <td><value :model="row" prop="takeUn"/></td>
                <td><value :model="row" prop="otherUn"/></td>
                <td><value :model="row" prop="unPayment"/></td>
                <td><value :model="row" prop="financeCheck"/></td>
                <td><value :model="row" prop="orderRemark"/></td>
              </tr>
              <tr>
                <td>合计</td>
                <td></td><td></td><td></td><td></td>
                <td>{{detail.checkOrderList.length}}</td><td></td>
                <td>{{unCollection}}</td>
                <td>{{kickbackUn}}</td>
                <td>{{pickUn}}</td>
                <td>{{transportUn}}</td>
                <td>{{takeUn}}</td>
                <td>{{otherUn}}</td>
                <td>{{unPayment}}</td>
                <td>{{financeCheck}}</td><td></td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>

    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>

    <el-dialog append-to-body :visible.sync="showDialogVisible">
      <div class="ad-block card">
        <el-form :model="formData" ref="formData" style="flex-direction: row">
          <div class="col" style="margin-top: 0">
            <div class="col-title">凭证</div>
            <el-form-item prop="imgList" :rules="{required: true, message:'请上传凭证'}">
              <el-upload action="" list-type="picture-card" multiple drag
                         :file-list="images"
                         :on-success="imageSuccess"
                         :http-request="uploadImages"
                         :on-remove="removeImage"
                         :on-preview="imagePreview"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>
          </div>
          <div>
            <div class="col">
              <div class="col-title">收付款时间</div>
              <div class="item">
                <el-form-item prop="realCollectionTime">
                  <el-date-picker size="mini"  placeholder="请选择" v-model="formData.realCollectionTime" value-format="timestamp" type="datetime" />
                </el-form-item>
              </div>
            </div>
            <div class="col">
              <div class="col-title">渠道</div>
              <div class="item">
                <el-form-item prop="channel" :rules="{required: true, message:'请选择渠道'}">
                  <el-select v-model.number="formData.channel" clearable>
                    <el-option v-for="type in dict.finance_channel" :key="type.id" :label="type.label" :value="Number(type.value)"/>
                  </el-select>
                </el-form-item>
              </div>
            </div>
            <div class="col">
              <div class="col-title">备注</div>
              <div class="item">
                <el-form-item prop="remark">
                  <el-input size="mini" placeholder="" v-model="formData.remark" style="width: 300px" />
                </el-form-item>
              </div>
            </div>
          </div>
        </el-form>
      </div>
      <el-button type="primary" @click="gotoSubmit" size="mini" style="float: right;position: relative;top: -10px;">保 存</el-button>
    </el-dialog>
  </div>
</template>

<script>
import Value from '@/components/AdValue'
import AdTable from '@/components/AdTable'
import AdTableColumn from '@/components/AdTable/AdTableColumn'
import { parseTime } from '@/utils'
import { parseStatus, parseCityCode } from '@/utils/code'
import { get, repeal,reconciliationSettle } from '@/api/finance/check/finish'
import { download } from '@/api/data'
import { downloadFile } from '@/utils/index'
import aliOSS from '@/utils/aliOss'
import adTable from '@/mixins/adTable'

export default {
  components: { AdTable, AdTableColumn, Value },
  dicts: ['payment_type','finance_channel'],
  mixins: [adTable([{name: 'order'}])],
  data() {
    return {
      images: [],
      formData: {
        imgList: [],
        realCollectionTime: new Date().getTime(),
        remark: ''
      },
      form: {},
      detail: null,
      showDialogVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      totalPdf: 1
    }
  },
  created() {
    get(this.$attrs.data.id).then(res => this.detail = res.data)
  },
  watch: {
    '$attrs.visible'(visible) {
      if (visible) {
        get(this.$attrs.data.id).then(res => this.detail = res.data)
      }
    }
  },
  computed: {
    unCollection() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.unCollection ? row.unCollection : 0), 0)
    },
    kickbackUn() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.kickbackUn ? row.kickbackUn : 0), 0)
    },
    pickUn() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.pickUn ? row.pickUn : 0), 0)
    },
    transportUn() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.transportUn ? row.transportUn : 0), 0)
    },
    takeUn() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.takeUn ? row.takeUn : 0), 0)
    },
    otherUn() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.otherUn ? row.otherUn : 0), 0)
    },
    unPayment() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.unPayment ? row.unPayment : 0), 0)
    },
    financeCheck() {
      return this.detail.checkOrderList.reduce((total, row) => total + (row.financeCheck ? row.financeCheck : 0), 0)
    },
    cannotEdit() {
      return this.orderSelectedRows.length == 0
    }
  },
  methods: { parseTime, parseStatus, parseCityCode,
    showSettlement() {
      this.showDialogVisible = true
    },
    async uploadImages(file) {
      return aliOSS.ossUploadFile(file, 'image')
    },
    imageSuccess(res, file, fileList) {
      this.images = fileList
      this.formData.imgList = this.images.map(img => img.response.data)
      this.$refs.formData.clearValidate('imgList')
    },
    removeImage(file, fileList) {
      this.deletedImages.push(file.url.split('/').reduce((cur, next, index) => {
        if (index >= 3) {
          return cur ? cur + '/' + next : next
        } else {
          return ''
        }
      }))
      this.images = fileList
    },
    imagePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    repeal() {

      this.$confirm(`确认撤消吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // type: 'warning'
      }).then(() => {
        let ids = this.orderSelectedRows.map(item => item.orderId)
        repeal( this.$attrs.data.id, ids ).then(res => {
          // this.$notify({ title: '撤消成功', type: 'success', duration: 2500 })
          this.$emit('update:visible', false)
          this.$emit('refresh')
        })
      }).catch(() => {})
    },
    exportExcel() {
      download(`/api/finance/check/download/${this.$attrs.data.id}`).then(res => {
        downloadFile(res.data, res.headers.downloadFileName, 'xlsx')
      })
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          crudCheck.settlement({
            settlementName: this.query[0].settlementUser,
            orderIdList: this.query.map(item => item.orderId),
            imageList: this.images.map(img => img.response.data),
            remark: this.form.remark
          }).then(res => {
            this.$notify({ title: '结算成功', type: 'success', duration: 2500 })
            this.$emit('refresh')
            this.$emit('update:show', false)
          })
        }
      })
    },
    gotoSubmit() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          reconciliationSettle({
            financeCheckIdList: this.orderSelectedRowIds,
            imageList: this.images.map(img => img.response.data),
            realCollectionTime: this.formData.realCollectionTime,
            channel: this.formData.channel,
            remark: this.formData.remark
          }).then(res => {
            this.$notify({ title: '结算成功', type: 'success', duration: 2500 })
            this.formData.imgList = []
            this.images = []
            this.formData.realCollectionTime = new Date().getTime()
            this.formData.remark = ''
            this.formData.channel = ''
            this.$refs.formData.resetFields()
            this.orderSelectedRowIds = []
            this.orderSelectedRows = []
            console.log(this.$refs)
            this.$refs.order.$refs.table.clearSelection()
            get(this.$attrs.data.id).then(res => this.detail = res.data)
            this.showDialogVisible = false
            this.$emit('refresh')
          })
        }
      })
    },
  }
}
</script>

<style lang="stylus" scoped>
.card
  margin-bottom: 20px
  font-size 12px
  display flex
  padding 16px 20px
  // overflow hidden
  .item-l
    position relative
    float left
    width 40px
    height 1px
    &:before
      content ''
      display block
      position absolute
      top -5px
      width 1px
      height 28px
      background #eaeaea
  .el-form
    display flex
    flex-direction column
    .col
      //margin-top 18px
      padding-left 0
      border-right none
    .item-l:before
      height 70px
  .item
    float left
    margin-right 36px
  .group
    float left
  .col
    float left
    border-right 1px solid #f5f5f5
    padding 0 34px
    &:first-child
      padding-left 0
    &:last-child
      padding-right 0
      border-right 0
    .col-title
      margin-bottom 12px
    .item
      float none
      margin-bottom 16px
      margin-right 0
      &:last-child
        margin-bottom 0
    .el-form-item
      display inline-block
      margin-bottom 0
  /deep/.el-upload-list__item
  /deep/.el-upload--picture-card
  .img
    width 90px
    height 54px
    line-height 58px
    margin-right 10px
    .el-upload-dragger
      width 100%
      height 100%
      border none
.form-btns
  text-align center
#print-table
  font-size 12px
  .print-table:not(:first-child)
    margin-top 36px
  .print-title
    font-size 20px
    text-align center
  .print-head
    margin 10px 0
    text-align left
    font-size 14px
    span
      margin-right 40px
  table
    border-collapse collapse
    th,td
      padding 5px 0
      text-align center
.total-pdf
  width 100px
  margin-left 10px
  /deep/.el-input__inner
    text-align center
</style>